package com.barunsw.bwf.bims.tool;

import java.util.List;
import java.util.concurrent.ScheduledFuture;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.concurrent.ConcurrentTaskScheduler;
import org.springframework.stereotype.Component;

import com.barunsw.bwf.bims.channel.ChannelDao;
import com.barunsw.bwf.bims.channel_history.ChannelHistoryDao;
import com.barunsw.bwf.bims.device.DeviceDao;
import com.barunsw.bwf.bims.vo.ChannelHistoryVo;
import com.barunsw.bwf.bims.vo.ChannelVo;
import com.barunsw.bwf.bims.vo.DeviceVo;

@Component
public class ChannelDataGenerator {
    private static final Logger LOGGER = LoggerFactory.getLogger(ChannelDataGenerator.class);

    private TaskScheduler scheduler = new ConcurrentTaskScheduler();
    private ScheduledFuture future;
    
    @Autowired
    private DeviceDao deviceDao;
    
    @Autowired
    private ChannelDao channelDao;

    @Autowired
    private ChannelHistoryDao channelHistoryDao;
    
	@PostConstruct
    public void run() {
		LOGGER.debug("ChannelDataGenerator run");
		
		future = scheduler.scheduleAtFixedRate(new Runnable() {
			@Override
			public void run() {
				//generateChannelData();
			}
		}, 10000);
    }
	
	@PreDestroy
	public void shutdown() {
		if ( future != null ) {
			future.cancel(true);
		}
	}
	
	private void generateChannelData() {
		List<DeviceVo> deviceData = deviceDao.selectList();
		for ( DeviceVo oneDevice : deviceData ) {
			List<ChannelVo> channelData = channelDao.selectList(oneDevice.getId());
			for ( ChannelVo oneChannel : channelData ) {
				double maxVal = oneChannel.getMaxVal();
				double minVal = oneChannel.getMinVal();

				double curVal = minVal + Math.random() * (maxVal-minVal);

				ChannelHistoryVo historyVo = new ChannelHistoryVo();
				historyVo.setId(oneChannel.getId());
				historyVo.setCurVal(curVal);
				
				LOGGER.debug(oneChannel.toString());

				channelHistoryDao.insertHistory(historyVo);
			}
		}
	}
}
